import { RouteOptions, RouteRecordRaw } from "vue-router";

export async function usePatchOptions(routes: RouteRecordRaw[]) {
  const urls = import.meta.glob("@/pages/**/routeOptions.ts");

  for (const key in urls) {
    const urlStr = key;
    const path = urlStr.split("/").reverse();
    // @ts-ignore
    const options: RouteOptions = (await urls[key]()).default;
    const routeOptions = options.routeOptions;
    const otherOptions = options.otherOptions;

    let index = path.length - 4;

    let children = routes;

    while (index > 0) {
      const route = children.find(
        (item) => item.name === path[index]
      ) as RouteRecordRaw;

      if (index === 1) {
        // 注册除去基础配置(path,name,component)外的路由配置
        if (routeOptions) {
          for (const optionKey in routeOptions) {
            //@ts-ignore
            route[optionKey] = routeOptions[optionKey];
          }
        }

        // 注册params参数
        if (otherOptions) {
          if (otherOptions.params) {
            route.path = `${route.path}/:${otherOptions.params}`;
          }
        }
      } else {
        children = route.children as RouteRecordRaw[];
      }

      index--;
    }
  }
}
